package faf.web.data;

import java.util.List;

import org.springframework.validation.Errors;
import org.springframework.validation.Validator;
import org.springframework.web.multipart.MultipartFile;

import faf.business.SheetManager;
import faf.business.SurveyManager;
import faf.entities.Properties;
import faf.entities.Question;
import faf.entities.Sheet;
import faf.entities.Survey;

public class SheetFormValidator implements Validator {
	SheetManager sheetManager;
	SurveyManager surveyManager;
	
	public void setSheetManager(SheetManager sheetManager) {
		this.sheetManager = sheetManager;
	}
	
	public void setSurveyManager(SurveyManager surveyManager){
		this.surveyManager = surveyManager;
	}

	@Override
	public boolean supports(Class clazz) {
		return SheetForm.class.equals(clazz);
	}

	@Override
	public void validate(Object command, Errors errors) {
		SheetForm sheetForm = (SheetForm) command;
		Sheet sheet = sheetManager.get(sheetForm.getIdSheet());
		Survey survey = sheet.getSurvey();
		List<Question> questions = surveyManager.findListQuestion(survey.getId());

		for (Question question : questions) {
			if(sheetForm.getAnswers().get(""+question.getId())  instanceof MultipartFile){
				MultipartFile file = (MultipartFile) sheetForm.getAnswers().get(""+question.getId());	
			}else {
				String answerValue = (String) sheetForm.getAnswers().get(""+question.getId());
				if(answerValue == null) errors.rejectValue( "answers["+question.getId()+"]", "obligatory-question");
				if(question.isObligatory() && answerValue != null){
					if(answerValue.isEmpty()){
						errors.rejectValue( "answers["+question.getId()+"]", "obligatory-question");
					} 
				}
				switch (question.getType()) {
					case STRING:
						break;
					case TEXT:
						break;
					case SIMPLECHOICE:
						boolean found = false;
						for(Properties p : question.getProperties()){
							if(p.getId() == Integer.parseInt(answerValue)) found= true;
						}
						if(found == false) errors.reject("propriete inconnue");
						break;
					default:
						errors.reject("type inconnu");
				}
			}
		}		
	}
}

